package spring.mymessage.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/ws/my-asset/{deptId}/{id}")
@Component
public class MyWebSocketServer {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @PostConstruct
    public void init() {
        System.out.println("myWebsocket 加载");
    }
    private static Logger log = LoggerFactory.getLogger(MyWebSocketServer.class);
    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    // concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
    //存储用户id
    private static ConcurrentHashMap<String, Session> userMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam(value = "deptId")String deptId, @PathParam(value = "id")String id) {
        SessionSet.add(session);
        userMap.put(getKey(deptId,id),session);
        // 在线数加1
        int cnt = OnlineCount.incrementAndGet();
        log.info("有连接加入，当前连接数为：{}", cnt);
        log.info("有连接加入，当前用户为:{}", getKey(deptId,id));
        SendMessage(session, "连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session,@PathParam(value = "deptId")String deptId, @PathParam(value = "id")String id) {
        SessionSet.remove(session);
        userMap.remove(getKey(deptId,id));
        int cnt = OnlineCount.decrementAndGet();
        log.info("有连接关闭，当前连接数为：{}", cnt);
        log.info("有连接关闭，当前用户池包含：{}个", userMap.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息：{}",message);
        SendMessage(session, "收到消息，消息内容："+message);
    }

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误：{}，Session ID： {}",error.getMessage(),session.getId());
        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     * @param message
     * @throws IOException
     */
    public static void BroadCastInfo(String message) throws IOException {
        for (Map.Entry<String, Session> mapSet : userMap.entrySet()) {
            Session session = mapSet.getValue();
            if (session.isOpen()){
                SendMessage(session, message);
            }
        }
    }

    /**
     * 指定Session发送消息
     * @param message
     * @throws IOException
     */
    public static void SendMessage(String message,String id) throws IOException {
        //Session session = userMap.get(id);
        Session session = getSessionById(id);
        if(session!=null){
            SendMessage(session, message);
        }
        else{
            log.warn("没有找到你指定ID的会话：{}",id);
        }
    }

    /**
     * 指定部门发送消息
     * @param message
     * @throws IOException
     */
    public static void sendMessageByDeptId(String message,String deptId) throws IOException {
        List<Session> list = getSessionByDeptId(deptId);
        if(list.size() > 0){
            for (Session session : list) {
                SendMessage(session, message);
            }
        }
        else{
            log.warn("没有找到你指定部门ID：{}",deptId);
        }
    }
    private String getKey(String deptId,String id){
        return deptId + "-" + id;
    }
    private static Session getSessionById(String id){
        for (Map.Entry<String, Session> entry : userMap.entrySet()) {
            if (entry.getKey().endsWith(id)){
                return entry.getValue();
            }
        }
        return null;
    }
    private static List<Session> getSessionByDeptId(String deptId){
        List<Session> sessions = new ArrayList<>();
        for (Map.Entry<String, Session> entry : userMap.entrySet()) {
            if (entry.getKey().startsWith(deptId)){
                sessions.add(entry.getValue());
            }
        }
        return sessions;
    }
    public void saveMessageByDeptId(String message,String deptId){
        //保存部门队列
        redisTemplate.opsForList().leftPush(RedisBlockingQueue.PREFIX+"."+ deptId, message);
    }
    public void saveMessageById(String message,String id){
        //保存用户队列
        redisTemplate.opsForList().leftPush(RedisBlockingQueue.PREFIX+"."+ id, message);
    }
}